package org.changs.aplug.widget.irecyclerview;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yincs on 2017/7/25.
 */


public abstract class SimpleAdapter<DATA, BINDING extends ViewDataBinding>
        extends RecyclerView.Adapter<SimpleAdapter.MyViewHolder<BINDING>>
        implements IIRecyclerView.IDataAdapter<DATA> {

    private List<DATA> data;

    private final int layoutRes;

    private int selectIndex = -1;

    public SimpleAdapter(@LayoutRes int layoutRes) {
        this(null, layoutRes);
    }

    public SimpleAdapter(List<DATA> data, @LayoutRes int layoutRes) {
        this.layoutRes = layoutRes;
        this.data = data;
        if (this.data == null)
            this.data = new ArrayList<>();
    }

    @Override
    public MyViewHolder<BINDING> onCreateViewHolder(ViewGroup parent, int viewType) {
        BINDING binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), layoutRes, parent, false);
        return new MyViewHolder<>(binding);
    }


    @Override
    public final void onBindViewHolder(MyViewHolder<BINDING> holder, int position) {
        onBindViewHolder(holder.binding, position);
        if (selectIndex != -1) {
            if (selectIndex == position) {
                holder.itemView.setSelected(true);
            } else {
                holder.itemView.setSelected(false);
            }
        }
    }

    public void setSelectIndex(int selectIndex) {
        this.selectIndex = selectIndex;
    }

    public int getSelectPosition() {
        return selectIndex;
    }

    public boolean isSelect(int position) {
        return position == selectIndex;
    }

    public abstract void onBindViewHolder(BINDING binding, int position);

    public DATA getSelectItem() {
        if (selectIndex < 0 || selectIndex >= data.size())
            return null;
        return data.get(selectIndex);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public List<DATA> getData() {
        return data;
    }

    public static class MyViewHolder<BINDING extends ViewDataBinding> extends RecyclerView.ViewHolder {

        public BINDING binding;

        public MyViewHolder(BINDING binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}
